
const { createWorker, createScheduler } = require('tesseract.js')
// const sharp = require('sharp');


// async function preprocessImage(imagePath) {
//     return new Promise((resolve, reject) => {
//         sharp(imagePath)
//             .grayscale() // 转换为灰度图像
//             .threshold(128) // 二值化处理
//             .toBuffer((err, buffer, info) => {
//                 resolve(buffer)
//             });
//     })
// }

let worker = [{}, {}, {}, {}, {}]
let fun = async () => {
    worker.forEach(async (item, index) => {
        worker[index] = await createWorker('eng')
        await worker[index].setParameters({
            tessedit_char_whitelist: '0123456789.,()０１２３４５６７８９．，（）',
        });
    })

}
fun()
let worker2 = [{}, {}, {}, {}, {}]
let arr = [
    '建邺城', '傲来国', '宝象国', '大唐境外',
    '女儿村', '普陀山', '五庄观', '西梁女国',
    '长寿村', '朱紫国', '江南野外'
]
let arr2 = [
    '出逃在', '附近', '帮我捉回来', '第个',
    ':', '：', '去', '处抓']
let arr3 = [
    '诌鬼', '假鬼', '奸鬼', '捣大鬼',
    '冒失鬼', '挖渣鬼', '仔细鬼', '讨吃鬼',
    '地哩鬼', '叫街鬼', '偷尸鬼', '寒碜鬼',
    '倒塌鬼', '涎脸鬼', '滴料鬼', '发贱鬼',
    '急急鬼', '耍碗鬼', '低达鬼', '遭瘟鬼',
    '轻薄鬼', '浇虚鬼', '绵缠鬼', '黑眼鬼',
    '龌龊鬼', '温斯鬼', '不通鬼', '诓骗鬼',
    '急赖鬼', '心病鬼', '醉死鬼', '抠掐鬼',
    '伶俐鬼', '急突鬼', '丢谎鬼', '乜斜鬼',
    '撩桥鬼'
];
let arr4 = [
    '子时', '丑时', '寅时', '卯时',
    '辰时', '巳时', '午时', '未时',
    '申时', '酉时', '戌时', '亥时'
];
let arr5 = [
    "一刻", "二刻", "三刻", "四刻",
    "五刻", "六刻", "七刻", "八刻"]

let str = arr.join('') + arr2.join('') + arr3.join('') + arr4.join('') + arr5.join('')
let fun2 = async () => {
    worker2.forEach(async (item, index) => {
        worker2[index] = await createWorker('chi_sim')
        await worker2[index].setParameters({
            tessedit_char_whitelist: '0123456789.,()０１２３４５６７８９．，（）' + str,
        });
    })
}
fun2()
let worker3 = [{}, {}, {}, {}, {}]
let fun3 = async () => {
    worker3.forEach(async (item, index) => {
        worker3[index] = await createWorker('chi_sim')
        // await item.setParameters({
        //     tessedit_char_whitelist: '0123456789.,()０１２３４５６７８９．，（）' + str,
        // });
    })
}
fun3()
// 服务器的入口文件
// 1.创建KOA的实例对象
const Koa = require('koa')
const app = new Koa()
const bodyParser = require('koa-bodyparser')

app.use(
    bodyParser({
        formLimit: '10mb',
        jsonLimit: '10mb',
        textLimit: '10mb',
        xmlLimit: '10mb',
    })
)
// 开发
app.use(async (ctx, next) => {
    let body = ctx.request.body
    const buffer = Buffer.from(body.base64, 'base64');
    let worker_now
    if (body?.all) {
        worker_now = worker2
    } else if (body?.all2) {
        worker_now = worker3
        let fun = async () => {
            const [res, res2, res3, res4, res5] = await Promise.all([
                worker_now[0].recognize(buffer),
                worker_now[1].recognize(buffer),
                worker_now[2].recognize(buffer),
                worker_now[3].recognize(buffer),
                worker_now[4].recognize(buffer),

            ]);
            if (res.data.text == res2.data.text && res.data.text == res3.data.text && res.data.text == res4.data.text && res.data.text == res5.data.text) {
                ctx.body = (res.data.text + '').replace(/\n/g, '') + '';
                return
            } else {
                await fun()
            }
        }
        await fun()
        return
    } else {
        // 不在需要识别坐标
        // worker_now = worker // 坐标 
    }
    // let buffer_hui = await preprocessImage(buffer)
    // let fun2 = async () => {
    //     const [res, res2, res3, res4, res5] = await Promise.all([
    //         worker_now[0].recognize(buffer_hui),
    //         worker_now[1].recognize(buffer_hui),
    //         worker_now[2].recognize(buffer_hui),
    //         worker_now[3].recognize(buffer_hui),
    //         worker_now[4].recognize(buffer_hui),

    //     ]);
    //     if (res.data.text == res2.data.text && res.data.text == res3.data.text && res.data.text == res4.data.text && res.data.text == res5.data.text) {
    //         ctx.body = (res.data.text + '').replace(/\n/g, '') + '';
    //         return
    //     } else {
    //         await fun2()
    //     }
    // }
    // await fun2()
})


// 2.绑定中间件
// 绑定第一层中间件
const respDurationMiddleware = require('./middleware/koa_response_duration')
app.use(respDurationMiddleware)
// 绑定第二层中间件
const respHeaderMiddleware = require('./middleware/koa_response_header')
app.use(respHeaderMiddleware)
// 绑定第三层中间件
const respDataMiddleware = require('./middleware/koa_response_data')
app.use(respDataMiddleware)
// 3.绑定端口号 8888
app.listen(8888)

// const webSocketService = require('./service/web_socket_service')
// 开启服务端的监听 , 监听客户端的链接
// 当 某一个客户端链接成功之后 , 就会对这个客户端进行message事件的监听
// webSocketService.listen()
